<template>
  <div class="training-detail">
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
          <span class="title">培训建议详情</span>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>
      
      <div v-else-if="trainingData" class="detail-content">
        <!-- 基本信息 -->
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="培训建议ID">
            {{ trainingData.id }}
          </el-descriptions-item>
          <el-descriptions-item label="司机ID">
            {{ trainingData.driver_id }}
          </el-descriptions-item>
          <el-descriptions-item label="培训类型">
            <el-tag :type="getTrainingTypeColor(trainingData.recommendation_type)">
              {{ trainingData.recommendation_type }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityColor(trainingData.priority)">
              {{ getPriorityText(trainingData.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusColor(trainingData.status)">
              {{ getStatusText(trainingData.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatTime(trainingData.created_time) }}
          </el-descriptions-item>
          <el-descriptions-item v-if="trainingData.pushed_time" label="推送时间">
            {{ formatTime(trainingData.pushed_time) }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 培训内容 -->
        <el-card class="content-card" style="margin-top: 20px;">
          <template #header>
            <span class="content-title">培训内容</span>
          </template>
          <div class="training-content">
            <div class="content-text">{{ formatTrainingContent(trainingData.recommendation_content) }}</div>
          </div>
        </el-card>

        <!-- 培训材料 -->
        <el-card class="content-card" style="margin-top: 20px;">
          <template #header>
            <span class="content-title">培训材料</span>
          </template>
          <div class="training-materials">
            <div v-if="trainingMaterials.length > 0">
              <div v-for="(material, index) in trainingMaterials" :key="index" class="material-item">
                <el-tag type="info" style="margin-right: 10px;">材料 {{ index + 1 }}</el-tag>
                <span>{{ formatTrainingMaterial(material) }}</span>
              </div>
            </div>
            <el-empty v-else description="暂无培训材料" />
          </div>
        </el-card>

        <!-- 操作按钮 -->
        <div class="action-buttons" style="margin-top: 20px;">
          <el-button 
            v-if="trainingData.status === 0" 
            type="success" 
            @click="pushTrainingRecommendation"
            :loading="pushLoading"
          >
            推送培训建议
          </el-button>
          <el-button 
            v-if="trainingData.status === 1" 
            type="primary" 
            @click="markAsViewed"
            :loading="updateLoading"
          >
            标记为已查看
          </el-button>
          <el-button 
            v-if="trainingData.status === 2" 
            type="success" 
            @click="markAsCompleted"
            :loading="updateLoading"
          >
            标记为已完成
          </el-button>
        </div>
      </div>
      
      <div v-else class="error-container">
        <el-empty description="未找到培训建议数据" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { evaluationAPI } from '@/api/evaluation'

const route = useRoute()
const router = useRouter()

const trainingData = ref(null)
const trainingMaterials = ref([])
const loading = ref(true)
const pushLoading = ref(false)
const updateLoading = ref(false)

// 获取培训建议详情
async function loadTrainingDetail() {
  const trainingId = route.params.id
  if (!trainingId) {
    ElMessage.error('无效的培训建议ID')
    return
  }

  loading.value = true
  try {
    // 获取所有培训建议，然后找到对应的
    const response = await evaluationAPI.getTrainingRecommendations()
    if (response.data && response.data.data) {
      // 直接在所有数据中查找目标培训建议
      const found = response.data.data.find(item => item.id == trainingId)
      
      if (found) {
        trainingData.value = found
        // 解析培训材料
        if (found.training_materials) {
          try {
            if (typeof found.training_materials === 'string') {
              // 尝试解析JSON字符串
              try {
                const parsed = JSON.parse(found.training_materials)
                if (parsed.videos && Array.isArray(parsed.videos)) {
                  trainingMaterials.value = parsed.videos
                } else if (Array.isArray(parsed)) {
                  trainingMaterials.value = parsed
                } else {
                  // 如果是对象，只提取值，不显示键名
                  trainingMaterials.value = Object.values(parsed).flat()
                }
              } catch (parseError) {
                // 如果解析失败，直接使用原始字符串
                trainingMaterials.value = [found.training_materials]
              }
            } else if (Array.isArray(found.training_materials)) {
              trainingMaterials.value = found.training_materials
            } else {
              // 如果是对象，只提取值，不显示键名
              trainingMaterials.value = Object.values(found.training_materials).flat()
            }
          } catch (e) {
            console.error('解析培训材料失败:', e)
            trainingMaterials.value = [String(found.training_materials)]
          }
        }
        console.log('找到培训建议:', found)
      } else {
        console.log('未找到培训建议，ID:', trainingId)
        console.log('所有培训建议:', response.data.data)
        ElMessage.error(`未找到ID为 ${trainingId} 的培训建议`)
      }
    }
  } catch (error) {
    console.error('加载培训建议详情失败:', error)
    ElMessage.error('加载培训建议详情失败')
  } finally {
    loading.value = false
  }
}

// 推送培训建议
async function pushTrainingRecommendation() {
  if (!trainingData.value) return
  
  pushLoading.value = true
  try {
    const response = await evaluationAPI.pushTrainingRecommendation(trainingData.value.id)
    if (response.data && response.data.message) {
      ElMessage.success('培训建议推送成功')
      await loadTrainingDetail()
    } else {
      ElMessage.error(response.data?.error || '推送失败')
    }
  } catch (error) {
    console.error('推送培训建议失败:', error)
    ElMessage.error('推送失败')
  } finally {
    pushLoading.value = false
  }
}

// 标记为已查看
async function markAsViewed() {
  if (!trainingData.value) return
  
  updateLoading.value = true
  try {
    const response = await evaluationAPI.updateTrainingRecommendationStatus(trainingData.value.id, 2)
    if (response.data && response.data.message) {
      ElMessage.success('状态更新成功')
      await loadTrainingDetail()
    } else {
      ElMessage.error(response.data?.error || '更新失败')
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新失败')
  } finally {
    updateLoading.value = false
  }
}

// 标记为已完成
async function markAsCompleted() {
  if (!trainingData.value) return
  
  updateLoading.value = true
  try {
    const response = await evaluationAPI.updateTrainingRecommendationStatus(trainingData.value.id, 3)
    if (response.data && response.data.message) {
      ElMessage.success('状态更新成功')
      await loadTrainingDetail()
    } else {
      ElMessage.error(response.data?.error || '更新失败')
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新失败')
  } finally {
    updateLoading.value = false
  }
}

// 返回
function goBack() {
  router.back()
}

// 格式化时间
function formatTime(timeStr) {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN')
}

// 获取培训类型颜色
function getTrainingTypeColor(type) {
  switch (type) {
    case '服务态度':
      return 'success'
    case '驾驶技术':
      return 'info'
    case '车辆状况':
      return 'warning'
    case '沟通能力':
      return 'primary'
    case '时间观念':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取优先级颜色
function getPriorityColor(priority) {
  switch (priority) {
    case 1:
      return 'info'
    case 2:
      return 'warning'
    case 3:
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态颜色
function getStatusColor(status) {
  switch (status) {
    case 0:
      return 'info'
    case 1:
      return 'success'
    case 2:
      return 'warning'
    case 3:
      return 'success'
    default:
      return 'info'
  }
}

// 获取优先级文本
function getPriorityText(priority) {
  switch (priority) {
    case 1:
      return '低'
    case 2:
      return '中'
    case 3:
      return '高'
    default:
      return '未知'
  }
}

// 获取状态文本
function getStatusText(status) {
  switch (status) {
    case 0:
      return '未推送'
    case 1:
      return '已推送'
    case 2:
      return '已查看'
    case 3:
      return '已完成'
    default:
      return '未知'
  }
}

// 格式化培训内容
function formatTrainingContent(content) {
  if (!content) return '暂无培训内容'
  
  if (typeof content === 'string') {
    // 去掉Markdown符号
    return content
      .replace(/^#{1,6}\s*/gm, '') // 去掉标题的#号
      .replace(/\*\*(.*?)\*\*/g, '$1') // 去掉粗体的**号
      .replace(/\*(.*?)\*/g, '$1') // 去掉斜体的*号
      .replace(/^###\s*/gm, '') // 去掉三级标题
      .replace(/^####\s*/gm, '') // 去掉四级标题
      .replace(/^-\s*/gm, '• ') // 将-替换为• 
      .trim()
  } else if (typeof content === 'object' && content !== null) {
    // 如果是对象，尝试转换为可读格式
    try {
      if (content.title) {
        let result = `${content.title}\n\n`
        if (content.description) {
          result += `${content.description}\n\n`
        }
        if (content.sections) {
          content.sections.forEach((section, index) => {
            result += `${index + 1}. ${section.title}\n`
            if (section.content) {
              result += `${section.content}\n\n`
            }
          })
        }
        return result
      } else {
        // 如果没有特定结构，转换为JSON字符串
        return JSON.stringify(content, null, 2)
      }
    } catch (e) {
      return JSON.stringify(content, null, 2)
    }
  }
  
  return String(content)
}

// 格式化培训材料
function formatTrainingMaterial(material) {
  if (!material) return '暂无材料'
  
  if (typeof material === 'string') {
    return material
  } else if (typeof material === 'object' && material !== null) {
    // 如果是对象，转换为可读格式
    try {
      if (Array.isArray(material)) {
        return material.join(', ')
      } else {
        // 只显示值，不显示键名
        return Object.values(material).flat().join(', ')
      }
    } catch (e) {
      return JSON.stringify(material, null, 2)
    }
  }
  
  return String(material)
}

onMounted(() => {
  loadTrainingDetail()
})
</script>

<style scoped>
.training-detail {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.detail-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.loading-container {
  padding: 20px;
}

.detail-content {
  padding: 20px 0;
}

.content-card {
  border-radius: 8px;
}

.content-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.training-content {
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 16px;
  margin-top: 10px;
}

.content-text {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Microsoft YaHei', 'PingFang SC', sans-serif;
  font-size: 14px;
  line-height: 1.8;
  color: #606266;
  text-align: justify;
}

.training-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
}

.training-materials {
  margin-top: 10px;
}

.material-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409EFF;
}

.material-item .el-tag {
  flex-shrink: 0;
  margin-right: 12px;
  margin-top: 2px;
}

.material-item span {
  flex: 1;
  line-height: 1.6;
  color: #606266;
  word-wrap: break-word;
}

.action-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.error-container {
  padding: 40px;
  text-align: center;
}
</style> 